package com.kelai.service;

import javafx.util.Callback;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * 缓存服务
 * Created by Silence on 2016/10/21.
 */
@Service("cacheService")
public class CacheService implements InitializingBean {

    private final static Logger logger = LoggerFactory.getLogger(CacheService.class);

    private Map<String, CacheStore> cacheStore = new HashMap<>();

    private final JdbcTemplate jdbcTemplate;

    @Resource
    private Environment environment;

    @Autowired
    public CacheService(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public Object getCacheValue(String cacheId, String key, Callback<Object, Object> cb) {
        CacheStore store = cacheStore.get(cacheId);
        if (store != null) {
            if (cb != null)
                return cb.call(store.get(key));
            else
                return store.get(key);
        }
        return null;
    }

    @Override
    public void afterPropertiesSet() throws Exception {

    }

    static class CacheStore {
        String id;
        Map<String, Object> store;

        public CacheStore() {
            store = new HashMap<>();
        }

        public void add(String id, Object o) {
            store.putIfAbsent(id, o);
        }

        public Object get(String id) {
            return store.get(id);
        }
    }
}
